package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的明文密码进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    public void save(EmployeeDTO employeeDTO) {
        //将dto对象转为实体
        Employee employee = new Employee();
        //使用BeanUtils工具类
        BeanUtils.copyProperties(employeeDTO,employee);

        //设置状态 1表示开启 0表示锁定
        employee.setStatus(StatusConstant.ENABLE);

        //设置密码，默认123456，员工可自己修改
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes(StandardCharsets.UTF_8)));

        //调用Mapper层方法访问数据库
        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //select * from employee limit 0 10

        //开始分页查询，使用mybatis提供的PageHelper插件，向pageQuery调用的sql方法后拼接limit（分页查询）
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        //调用mapper层方法，向数据库查询,Page是PageHelper中的对象
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        //获取查询的总条目数，调用该方法后，mybatis会自动执行一条查询所有的sql
        long total = page.getTotal();

        //获取分页查询的结果
        List<Employee> records = page.getResult();

        return new PageResult(total,records);
    }

    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        //update employee set status = ? where id = ?

        /*Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);*/

        //这里用动态sql，一条修改sql语句，执行所有修改操作
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();

        employeeMapper.update(employee);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public Employee getById(Long id) {
        Employee employee= employeeMapper.getById(id);

        //在修改功能模块，若前端传回的信息中包含password字段请将employee.setPassword()设置为null/''，否则可以可以设置******等其他字符，来掩盖密码
        //此功能模块主要与修改员工信息功能模块搭配，作数据回显功能，发送修改请求时会将该回显的数据经过修改重新发送过来(此时密码为null/'')
        //而修改语句时动态修改sql，用于全局员工的修改功能,<if test="password != null and password != ''">password = #{password},</if>
        //所以此时不会修改原始密码，否则，若设置为 ****** 那么重新发送修改请求时(此时密码为 ****** )
        // 就会满足if条件，使密码改为******，而用户却不知道
        employee.setPassword("******");
        return employee;
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    public void updateMes(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();

        BeanUtils.copyProperties(employeeDTO,employee);

        //mapper层的update为动态sql，需要一个employee对象
        employeeMapper.update(employee);
    }
}
